<template>
  <el-card class="app-container">
    <!--    <el-row :gutter="10" type="flex">-->
    <!--      <el-col :span="6">-->
    <!--        <el-card shadow="never" style="margin-top: 20px">-->
    <!--          <div class="card_fitTitle">-->
    <!--            总撤销率-->
    <!--          </div>-->
    <!--          <div class="card-num">-->
    <!--            {{ totalRevocationRate }}-->
    <!--            <span class="card-unit">%</span>-->
    <!--          </div>-->
    <!--        </el-card>-->
    <!--      </el-col>-->
    <!--    </el-row>-->
    <!--    <line-chart :chart-data="lineChartData"/>-->
    <!--    <raddar-chart />-->
    <!--    <pie-chart/>-->
    <el-row :gutter="50" type="flex" style="margin-top: 40px">
      <el-col :span="12">
        <div>
          <el-form size="mini" inline>
            <el-form-item>
              <el-date-picker
                v-model="formData.dateRange4Store"
                type="daterange"
                range-separator="至"
                value-format="yyyy-MM-dd"
                style="width: 250px"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button @click="loadRevocationRateByStore" type="primary">搜索</el-button>
              <el-button @click="exportRevocationRateByStore" type="danger">导出</el-button>
            </el-form-item>
          </el-form>
          <div>
            <chart :option="storeBackoutRateOption"/>
            <el-table
              :summary-method="getSummaries"
              show-summary
              :data="revocationRateByStore"
              v-loading="revocationRateByStoreLoading"
              style="width: 100%">
              <el-table-column
                prop="storeTitle"
                label="店铺名"
                width="120">
              </el-table-column>
              <el-table-column
                prop="totalNum"
                label="跟进记录总数"
                width="120">
              </el-table-column>
              <el-table-column
                prop="backOutNum"
                label="撤销记录总数"
                width="120"
              >
              </el-table-column>
              <el-table-column
                prop="payOutAmount"
                label="赔付金额"
                width="120"
              >
                <template slot-scope="scope">
                  <div>￥{{ scope.row.payOutAmount }}</div>
                </template>
              </el-table-column>
              <el-table-column
                prop="rate"
                label="撤销率"
                width="auto">
                <template slot-scope="scope">
                  <div>{{ scope.row.rate * 100 | percentFormat }}%</div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-col>
      <el-col :span="12">

        <div>
          <el-form size="mini" inline>
            <el-form-item>
              <el-date-picker
                v-model="formData.dateRange4Follower"
                type="daterange"
                range-separator="至"
                value-format="yyyy-MM-dd"
                style="width: 250px"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button @click="loadRevocationRateByFollower" type="primary">搜索</el-button>
              <el-button @click="exportRevocationRateByFollower" type="danger">导出</el-button>
            </el-form-item>
          </el-form>
          <div>
            <chart :option="followerBackoutRateOption"/>
            <el-table
              :data="revocationRateByFollower"
              :summary-method="getSummaries2"
              show-summary
              v-loading="revocationRateByFollowerLoading"
              style="width: 100%">
              <el-table-column
                prop="followerName"
                label="跟进人"
                width="120">
              </el-table-column>
              <el-table-column
                prop="backOutNum"
                label="撤销记录总数"
                width="120"
              >
              </el-table-column>
              <el-table-column
                prop="totalNum"
                label="跟进记录总数"
                width="120">
              </el-table-column>

              <el-table-column
                prop="payOutAmount"
                label="赔付金额"
                width="120"
              >
                <template slot-scope="scope">
                  <div>￥{{ scope.row.payOutAmount }}</div>
                </template>
              </el-table-column>
              <el-table-column
                prop="rate"
                label="撤销率"
                width="auto">
                <template slot-scope="scope">
                  <div>{{ scope.row.rate * 100 | percentFormat }}%</div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-col>
    </el-row>
    <loading-dialog v-model="isExporting" loading-text="正在导出，请稍等"/>
  </el-card>
</template>

<script>
import {voteBadCommentApi} from "@/feature/cmt/infra/api/voteBadCommentApi";
import LineChart from "@/components/chart/LineChart";
import RaddarChart from "@/components/chart/RaddarChart";
import PieChart from "@/components/chart/PieChart";
import BarChart from "@/components/chart/BarChart";
import Chart from "@/components/chart/Chart";
import ObjectUtil from "@/framework/infra/object/ObjectUtil";
import ColumnUtil from "@/framework/components/table/ColumnUtil";
import ExcelUtil from "@/framework/infra/excel/ExcelUtil";
import LoadingDialog from "@/framework/components/dialog/LoadingDialog";

export default {
  components: {LoadingDialog, Chart, BarChart, PieChart, RaddarChart, LineChart},
  created() {
    // this.loadTotalRevocationRate()
    this.loadRevocationRateByStore()
    this.loadRevocationRateByFollower()

  },
  filters: {
    percentFormat(v) {
      return v.toFixed(2)
    }
  },
  computed: {
    storeBackoutRateOption() {
      return {
        title: {
          text: '店铺差评撤销率'
        },
        // toolbox: {
        //   feature: {
        //     dataView: { show: true, readOnly: false },
        //     restore: { show: true },
        //     saveAsImage: { show: true }
        //   }
        // },
        // legend: {
        //   data: ['撤销率']
        // },
        tooltip: {
          trigger: 'axis',
          formatter: params => {
            const param = params[0]
            return param.name + ' ' + param.marker + param.value + '%'
          },
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          axisTick: {
            alignWithLabel: true
          },
          data: this.revocationRateByStore.map(el => el.storeTitle)
        },
        yAxis: {
          type: 'value',
          axisTick: {
            show: false
          },
          axisLabel: {
            formatter: '{value} %'
          }
        },
        series: [
          {
            data: this.revocationRateByStore.map(el => (el.rate * 100).toFixed(2)),
            barWidth: '20%',
            type: 'bar',
            name: '撤销率',
            showBackground: true,

            backgroundStyle: {
              color: 'rgba(180, 180, 180, 0.2)'
            }
          }
        ]
      }
    },
    followerBackoutRateOption() {
      return {
        title: {
          text: '跟进人撤销率'
        },
        // toolbox: {
        //   feature: {
        //     dataView: { show: true, readOnly: false },
        //     restore: { show: true },
        //     saveAsImage: { show: true }
        //   }
        // },
        // legend: {
        //   data: ['撤销率']
        // },
        tooltip: {
          trigger: 'axis',
          formatter: params => {
            const param = params[0]
            return param.name + ' ' + param.marker + param.value + '%'
          },
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          axisTick: {
            alignWithLabel: true
          },
          data: this.revocationRateByFollower.map(el => el.followerName)
        },
        yAxis: {
          type: 'value',
          max: 100,
          axisTick: {
            show: false
          },
          axisLabel: {
            formatter: '{value} %'
          }
        },
        series: [
          {
            data: this.revocationRateByFollower.map(el => (el.rate * 100).toFixed(2)),
            barWidth: '20%',
            type: 'bar',
            name: '撤销率',
            showBackground: true,

            backgroundStyle: {
              color: 'rgba(180, 180, 180, 0.2)'
            }
          }
        ]
      }
    }
  },
  data() {
    return {
      isExporting: false,
      formData: {
        dateRange4Store: [],
        dateRange4Follower: []
      },
      totalRevocationRate: 0,
      revocationRateByStoreLoading: false,
      revocationRateByFollowerLoading: false,
      revocationRateByStore: [],
      revocationRateByFollower: []
      // ,
      // lineChartData: {
      //   expectedData: [100, 120, 161, 134, 105, 160, 165],
      //   actualData: [120, 82, 91, 154, 162, 140, 145]
      // }
    }
  },
  methods: {
    // loadTotalRevocationRate() {
    //   voteBadCommentApi.queryTotalRevocationRate().then(data => {
    //     this.totalRevocationRate = data * 100
    //   })
    // },
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          if (column.property === 'payOutAmount') {
            sums[index] = '￥' + sums[index];
          }
          if (column.property === 'rate') {
            sums[index] = (sums[index] / values.length * 100).toFixed(2) + '%';
          }
        } else {
          sums[index] = 'N/A';
        }
      });

      return sums;
    },
    getSummaries2(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计';
          return;
        }


        const values = data.map(item => Number(item[column.property]));

        if (!values.every(value => isNaN(value))) {
          if (column.property === 'totalNum') {
            sums[index] = values[0]
          } else {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            if (column.property === 'payOutAmount') {
              sums[index] = '￥' + sums[index];
            }
            if (column.property === 'rate') {
              sums[index] = '100.00%';
            }
          }
        } else {
          sums[index] = 'N/A';
        }
      });

      return sums;
    },
    exportRevocationRateByStore() {
      this.isExporting = true
      voteBadCommentApi.queryRevocationRateByStore(this.formData.dateRange4Store).then(data => {
        const header = ['店铺名', '跟进记录总数', '撤销记录总数', '赔付金额', '撤销率']
        const exportedData = []
        if (data && data.length) {
          for (const row of data) {
            exportedData.push([row.storeTitle, row.totalNum, row.backOutNum, row.payOutAmount, (row.rate * 100).toFixed(2) + '%'])
          }
          exportedData.push(['合计', exportedData.map(row => row[1]).reduce((r, a) => r + a, 0), exportedData.map(row => row[2]).reduce((r, a) => r + a, 0), exportedData.map(row => row[3]).reduce((r, a) => r + a, 0), (exportedData.map(row => parseFloat(row[4])).reduce((r, a) => r + a, 0) / exportedData.length).toFixed(2) + '%'])
          // exportedData.push(['合计', row.totalNum, row.backOutNum, row.payOutAmount, (row.rate * 100).toFixed(2) + '%'])
        }
        ExcelUtil.exportTable({
          header,
          data: exportedData,
          filename: '店铺差评撤销率统计'
        })
      }).finally(() => {
        this.isExporting = false
      })
    },
    loadRevocationRateByStore() {
      this.revocationRateByStoreLoading = true
      voteBadCommentApi.queryRevocationRateByStore(this.formData.dateRange4Store).then(data => {
        this.revocationRateByStore = data
      }).finally(() => {
        this.revocationRateByStoreLoading = false
      })
    },
    loadRevocationRateByFollower() {
      this.revocationRateByFollowerLoading = true
      voteBadCommentApi.queryRevocationRateByFollowerId(this.formData.dateRange4Follower).then(data => {
        this.revocationRateByFollower = data
      }).finally(() => {
        this.revocationRateByFollowerLoading = false
      })
    },
    exportRevocationRateByFollower() {
      this.isExporting = true
      voteBadCommentApi.queryRevocationRateByFollowerId(this.formData.dateRange4Follower).then(data => {
        const header = ['跟进人', '跟进记录总数', '撤销记录总数', '赔付金额', '撤销率']
        const exportedData = []
        if (data && data.length) {
          for (const row of data) {
            exportedData.push([row.followerName, row.totalNum, row.backOutNum, row.payOutAmount, (row.rate * 100).toFixed(2) + '%'])
          }
          exportedData.push(['合计', exportedData.map(row => row[1]).reduce((r, a) => r + a, 0), exportedData.map(row => row[2]).reduce((r, a) => r + a, 0), exportedData.map(row => row[3]).reduce((r, a) => r + a, 0), (exportedData.map(row => parseFloat(row[4])).reduce((r, a) => r + a, 0) / exportedData.length).toFixed(2) + '%'])
        }
        ExcelUtil.exportTable({
          header,
          data: exportedData,
          filename: '跟进人差评撤销率统计'
        })
      }).finally(() => {
        this.isExporting = false
      })
    }
  }
}
</script>

<style scoped lang="scss">

.card_fitTitle {
  font-size: 14px;
  color: #999;
  padding-bottom: 10px;

}

.center {
  text-align: center;
}

.card-num {
  font-size: 24px;
  padding-bottom: 10px;
}

.card-unit {
  font-size: 12px;
}

.news {

  &__sep {
    margin: 0 15px;
  }

  &__content {
    color: #999;
  }

}

.card-txt {
  font-size: 14px;
}

.short-cut {
  text-align: center;
  font-size: 14px;
  margin-bottom: 15px;
  float: left;
  margin-right: 30px;
}

.short-cuts-content {
  overflow: hidden;
  box-sizing: border-box;
}

.short-icon {
  display: block;
  font-size: 30px;
  margin-bottom: 5px;
}

.short-cuts-title {
  padding-bottom: 30px;
}

.todolist {
  padding: 50px 0 10px 0;
}

.todolist .el-row {
  padding-bottom: 15px;
}

.todo-title {
  padding-bottom: 30px;
  font-size: 18px;
  font-weight: bold;
}

.short-cuts-title {
  font-size: 18px;
  font-weight: bold;
}

.todo-block {
  text-align: center;
  display: inline-block;
  width: 120px;
  margin-bottom: 20px;
}

.todo-txt {
  font-size: 14px;
}

.todo-block .todo-num {
  font-size: 18px;
  padding-bottom: 10px;
}
</style>
